<template>
  <div class="panel">
    <div ref="chartRef" class="chart"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'

const chartRef = ref<HTMLElement | null>(null)
let chart: echarts.ECharts | null = null

const initChart = () => {
  if (!chartRef.value) return
  
  chart = echarts.init(chartRef.value)
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: '5%',
      top: 'center',
      itemGap: 20,
      textStyle: {
        rich: {
          name: {
            color: '#33ffd0'
          },
          value: {
            color: '#ffffff',
            textShadow: '0 0 10px rgba(255, 255, 255, 0.5)'
          }
        }
      },
      formatter: function(name: string) {
        const data = option.series[0].data;
        const target = data.find((item: any) => item.name === name);
        const value = target ? target.value : '';
        return [
          '{name|' + name + '}',
          '{value|' + value + '%}'
        ].join('              ');
      }
    },
    series: [
      {
        name: '作物生长状态',
        type: 'pie',
        radius: ['10%', '90%'],
        center: ['20%', '50%'],
        roseType: 'area',
        itemStyle: {
          borderRadius: 0
        },
        label: {
          show: false
        },
        data: [
          { value: 48.4, name: '生长良好', itemStyle: { color: '#67C23A' } },
          { value: 28.7, name: '生长一般', itemStyle: { color: '#409EFF' } },
          { value: 12.0, name: '需要关注', itemStyle: { color: '#E6A23C' } },
          { value: 7.6, name: '生长不良', itemStyle: { color: '#F56C6C' } },
          { value: 3.3, name: '严重问题', itemStyle: { color: '#ff0000' } }
        ]
      }
    ]
  }
  
  chart.setOption(option)
}

// 监听窗口大小变化
const handleResize = () => {
  chart?.resize()
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  chart?.dispose()
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.panel {
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart {
  width: 100%;
  height: 100%;
}
</style> 